package com.lb.pdm.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lb.pdm.common.constants.RedisConstants;
import com.lb.pdm.common.result.GraceJSONResult;
import com.lb.pdm.entity.CertificateApplication;
import com.lb.pdm.entity.CertificateInfo;
import com.lb.pdm.entity.PersonInfo;
import com.lb.pdm.entity.SysUser;
import com.lb.pdm.entity.bo.CertificateApplicationApproval;
import com.lb.pdm.entity.bo.CertificateApplicationBO;
import com.lb.pdm.entity.bo.CertificateApplicationQuery;
import com.lb.pdm.entity.vo.CertificateApplicationVO;
import com.lb.pdm.mapper.CertificateApplicationMapper;
import com.lb.pdm.mapper.CertificateInfoMapper;
import com.lb.pdm.mapper.PersonInfoMapper;
import com.lb.pdm.service.CertificateApplicationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 证件申请表 服务实现类
 * </p>
 *
 * @author pdm
 * @since 2025-10-29
 */
@Service
public class CertificateApplicationServiceImpl extends ServiceImpl<CertificateApplicationMapper, CertificateApplication> implements CertificateApplicationService {
    @Autowired
    private CertificateApplicationMapper certificateApplicationMapper;
    @Autowired
    private PersonInfoMapper personInfoMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private CertificateInfoMapper certificateInfoMapper;


    @Override
    public GraceJSONResult apply(CertificateApplicationBO certificateApplicationBO, String token) {
        CertificateApplication certificateApplication = new CertificateApplication();
        BeanUtils.copyProperties(certificateApplicationBO, certificateApplication);

        String personIdCard = certificateApplicationBO.getPersonIdCard();
        QueryWrapper<PersonInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id_card", personIdCard);
        PersonInfo personInfo = personInfoMapper.selectOne(queryWrapper);
        if (personInfo == null) {
            return GraceJSONResult.errorMsg("未找到该人员信息");
        }

        certificateApplication.setPersonId(personInfo.getId());
        certificateApplication.setApplicationDate(new Date());
        certificateApplication.setApplicationStatus((byte)1);
        certificateApplication.setCreateTime(new Date());
        certificateApplication.setUpdateTime(new Date());

        String sysUserString = redisTemplate.opsForValue().get(RedisConstants.USER_TOKEN_PREFIX + token);
        SysUser sysUser = JSON.parseObject(sysUserString, SysUser.class);
        certificateApplication.setCreateBy(sysUser.getId());
        certificateApplication.setUpdateBy(sysUser.getId());

        int insertRes = certificateApplicationMapper.insert(certificateApplication);
        if (insertRes <=  0) {
            return GraceJSONResult.errorMsg("申请失败");
        }

        return GraceJSONResult.ok();
    }

    @Override
    public List<CertificateApplicationVO> query(CertificateApplicationQuery certificateApplicationQuery) {
        String idCard = certificateApplicationQuery.getIdCard();
        String certificateType = certificateApplicationQuery.getCertificateType();
        Byte applicationType = certificateApplicationQuery.getApplicationType();
        Byte applicationStatus = certificateApplicationQuery.getApplicationStatus();
        Integer pageNum = certificateApplicationQuery.getPageNum();
        Integer pageSize = certificateApplicationQuery.getPageSize();
        Integer startIndex = (pageNum - 1) * pageSize;
        return certificateApplicationMapper.query(idCard, certificateType, applicationType, applicationStatus, startIndex, pageSize);
    }

    @Override
    @Transactional
    public GraceJSONResult approval(CertificateApplicationApproval certificateApplicationApproval, String token) {
        Long id = certificateApplicationApproval.getId();
        Byte applicationStatus = certificateApplicationApproval.getApplicationStatus();

        LambdaQueryWrapper<CertificateApplication> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CertificateApplication::getId, id);
        CertificateApplication certificateApplication = certificateApplicationMapper.selectOne(queryWrapper);

        certificateApplication.setApplicationStatus(applicationStatus);
        certificateApplication.setApprovalTime(new Date());
        certificateApplication.setUpdateTime(new Date());

        String sysUserString = redisTemplate.opsForValue().get(RedisConstants.USER_TOKEN_PREFIX + token);
        SysUser sysUser = JSON.parseObject(sysUserString, SysUser.class);

        certificateApplication.setUpdateBy(sysUser.getId());
        certificateApplication.setApprovalBy(sysUser.getId());

        int updateRes = certificateApplicationMapper.updateById(certificateApplication);
        if (updateRes <= 0) {
            return GraceJSONResult.errorMsg("审批失败");
        }

        CertificateInfo certificateInfo = new CertificateInfo();
        certificateInfo.setPersonId(certificateApplication.getPersonId());
        certificateInfo.setCertificateType(certificateApplication.getCertificateType());

        if (certificateApplication.getCertificateType().equals("身份证")) {
            LambdaQueryWrapper<PersonInfo> personInfoQuery = new LambdaQueryWrapper<>();
            personInfoQuery.eq(PersonInfo::getId, certificateApplication.getPersonId());
            PersonInfo personInfo = personInfoMapper.selectOne(personInfoQuery);
            certificateInfo.setCertificateNumber(personInfo.getIdCard());
        }else if (certificateApplication.getCertificateType().equals("居住证")) {
            certificateInfo.setCertificateNumber(UUID.randomUUID().toString());
        }

        certificateInfo.setIssueDate(new Date());
        // 默认现在时间加五年
        certificateInfo.setExpireDate(new Date(new Date().getTime() + 5 * 365 * 24 * 60 * 60 * 1000));
        certificateInfo.setIssueAuthority(sysUser.getStationName());
        certificateInfo.setIssuePlace(sysUser.getStationName());
        certificateInfo.setStatus((byte)1);
        certificateInfo.setCreateTime(new Date());
        certificateInfo.setUpdateTime(new Date());
        certificateInfo.setCreateBy(sysUser.getId());
        certificateInfo.setUpdateBy(sysUser.getId());

        int insertRes = certificateInfoMapper.insert(certificateInfo);
        if (insertRes <= 0) {
            return GraceJSONResult.errorMsg("审批失败");
        }

        return GraceJSONResult.ok();

    }
}
